package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 胡慧
 * @title: ApUserLoginServiceImpl
 * @projectName heima-leadnews
 * @description: TODO
 * @date 2021/3/217:35
 */
@Service
@Transactional
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //检查设备id是否为空
        if (dto.getEquipmentId() == null && StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //手机号和密码不为空时查询该用户是否存在
        if (!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            String salt=apUser.getSalt();
            String password=dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (password.equals(apUser.getPassword())){
            //    返回jwr
                //2.3.返回jwt
                Map<String, Object> map = new HashMap();
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("user", apUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
        //    设备登录
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }

    }
}
